define([
    "angular",
    "framework/utils/JSONPrettyFormat",
    'framework/dataGrid/DataGridModule',
    'framework/pagination/GillionPaginationModule',
    'framework/msg/GillionMsgModule',
    'framework/associate/GillionAssociateModule'
], function (angular, JSONPrettyFormat) {
    var RulePackageModule = angular.module('RulePackageModule', ['DataGridModule',
        'GillionPaginationModule',
        'GillionMsgModule',
        'GillionAssociateModule'
    ]);

    RulePackageModule.controller('RulePackageController', function ($scope, $timeout, $compile,Resource, $dataSourceManager, GillionMsg) {
        var rulePackageResource = Resource("/grule-manager/rulePackage/:id", {
            id: "@id"
        });

        $scope.showPageView = function () {
            $scope.showPage = true;
            $scope.showAdd = false;
            $scope.showEdit = false;
        };

        $scope.showPageView();

        $scope.searchRulePackage = function () {
            $scope.search = $scope.search || {};
            var params = angular.extend($scope.search);
            $dataSourceManager.dataSources.rulePackageSource.doRequestData(1, params);
        };

        $scope.onRemoveRecord = function (event, row) {
            GillionMsg.confirm('提示信息', '是否确定删除？', function(r){
                if (r) {
                    rulePackageResource.remove({
                        id: row.id
                    }, function (response) {
                        if (response.success) {
                            GillionMsg.alert("提示消息", "删除成功！");
                            $scope.searchRulePackage();
                        }
                    });
                }
            });
            return false;
        };

        function printLog(response) {
            var logDetail = response.success ? response.data : response.errorMessages[0],
                lines = logDetail.split("\n"),
                lineCount = lines.length,
                $logDetail = angular.element("#logDetail");
            $scope.logDetail = "";
            var printCount = 0;
            var print = function (lineBegin, lineEnd) {
                return function () {
                    var printLines = lines.slice(lineBegin, lineEnd);
                    angular.forEach(printLines, function (line) {
                        $scope.logDetail += line + "\n";
                    });
                    $logDetail.scrollTop( $logDetail[0].scrollHeight);
                };
            };
            var i = 0;
            while (printCount < lineCount) {
                var printLine = Math.random() * 10;
                var lineBegin = printCount;
                var lineEnd = printCount + printLine;
                printCount = printCount + printLine;
                $timeout(print(lineBegin, lineEnd), 300 * (i++));
            }
            return i;
        };

        $scope.compile = function (rowId) {
            GillionMsg.confirm('提示信息', '是否确定编译？',
                function (r) {
                   if (r) {
                       Resource("/grule-manager/rulePublish/compile/:id", {
                           id: "@id"
                       }, {
                           "get": {
                               "failHandler": false
                           }
                       }).get({
                           id: rowId
                       }, function (response) {
                           $scope.showClear = false;
                           var wait =  GillionMsg.wait("等待", "编译中。。。", true);
                           var i = printLog(response);
                           $timeout(function () {
                               $scope.showClear = true;
                               wait.close();
                               if (response.success) {
                                   GillionMsg.alert("提示", "编译成功");
                               } else {
                                   GillionMsg.alert("提示", "编译失败");
                               }
                           }, 300*(i++));
                       });
                   }
                }
            );
        };

        $scope.publish = function(row) {
            GillionMsg.showUrl({
                title: '用例选择',
                url: '/html/ruleExpression/unitCase',
                height: 480,
                data: row,
                onClose: function(data){
                    if(angular.isArray(data) && data.length > 0) {
                        var content = '<div>\n    <div>版本：<input ng-model="version"/></div>\n</div>',
                            html = $compile(content)($scope);
                        $scope.version = '';
                        GillionMsg.confirm("新的编辑版本", html, function(success) {
                            if (success) {
                                Resource("/grule-manager/rulePublish/publish/:id", {
                                    id: "@id"
                                }, {
                                    "get": {
                                        "failHandler": false
                                    }
                                }).get({
                                    id: row.id,
                                    unitCaseIds: data,
                                    version: $scope.version
                                }, function (response) {
                                    $scope.showClear = false;
                                    var wait =  GillionMsg.wait("等待", "发布中。。。", true);
                                    var i = printLog(response);
                                    $timeout(function () {
                                        $scope.showClear = true;
                                        wait.close();
                                        if (response.success) {
                                            GillionMsg.alert("提示", "发布成功");

                                            $scope.search = $scope.search || {};
                                            var params = angular.extend($scope.search);
                                            $dataSourceManager.dataSources.rulePackageSource.doRequestData(1, params);
                                        } else {
                                            GillionMsg.alert("提示", "发布失败");
                                        }
                                    }, 300*(i++));
                                });
                            }
                        });
                    }
                }
            });
        };

        $scope.test= function(row) {
            GillionMsg.showUrl({
                title: '用例选择',
                url: '/html/ruleExpression/unitCase',
                height: 480,
                data: row,
                onClose: function(data){
                    if(angular.isArray(data) && data.length > 0) {
                        Resource("/grule-manager/rulePublish/test/:id", {
                            id: "@id"
                        }, {
                            "get": {
                                "failHandler": false
                            }
                        }).get({
                            id: row.id,
                            unitCaseIds: data
                        }, function (response) {
                            $scope.showClear = false;
                            var wait =  GillionMsg.wait("等待", "测试中。。。", true);
                            var i = printLog(response);
                            $timeout(function () {
                                $scope.showClear = true;
                                wait.close();
                                if (response.success) {
                                    GillionMsg.alert("提示", "测试成功");
                                } else {
                                    GillionMsg.alert("提示", "测试失败");
                                }
                            }, 300*(i++));
                        });
                    }
                }
            });
        };

        $scope.clear = function () {
            $scope.logDetail = '';
        };

        $scope.showAddRulePackage = function () {
            $scope.showAdd = true;
            $scope.showEdit = false;
            $scope.showPage = false;

            var templateRulePackage = {
                "name": "【必填】",
                "groupId": "【必填】",
                "artifactId": "【必填】",
                "version": "【必填】",
                "conditions": "【json格式】",
                "businessModelId": "",
                "status": 0,
                "remark": ""
            };
            $scope.addRulePackage = JSONPrettyFormat(templateRulePackage);
        };

        $scope.showEditRulePackage = function () {
            $scope.showAdd = false;
            $scope.showEdit = true;
            $scope.showPage = false;
        };

        $scope.createRulePackage = function () {
            var addRulePackage = JSON.parse($scope.addRulePackage);
            if (addRulePackage.conditions) {
                addRulePackage.conditions = JSON.stringify(addRulePackage.conditions);
            }
            rulePackageResource.create(addRulePackage, function (response) {
                if (response.success) {
                    GillionMsg.alert("提示消息", "保存成功！");
                    $scope.search = $scope.search || {};
                    var params = angular.extend($scope.search);
                    $dataSourceManager.dataSources.rulePackageSource.doRequestData(1, params);
                    $scope.showPageView();
                } else if (response.success !== false) {
                    GillionMsg.alert("提示消息", "保存失败，请核对保存信息！");
                    return;
                }
            });
        };

        $scope.rulePackageRendered = function (grid) {
            grid.actions.edit = function (row) {
                rulePackageResource.get({
                    id: row.id
                }, function (result) {
                    delete result.$promise;
                    delete result.$resolved;
                    $scope.currId = result.id;
                    delete result.id;
                    if (result.conditions) {
                        result.conditions = JSON.parse(result.conditions);
                    }
                    $scope.editRulePackage = JSONPrettyFormat(result);
                    $scope.showEditRulePackage();
                });
            };
        };

        $scope.updateRulePackage = function () {
            var editRulePackage = JSON.parse($scope.editRulePackage);
            if (editRulePackage.conditions) {
                editRulePackage.conditions = JSON.stringify(editRulePackage.conditions);
            }
            editRulePackage.id = $scope.currId;
            rulePackageResource.update(editRulePackage, function (response) {
                if (response.success) {
                    GillionMsg.alert("提示消息", "更新成功！");
                    $scope.search = $scope.search || {};
                    var params = angular.extend($scope.search);
                    $dataSourceManager.dataSources.rulePackageSource.doRequestData(1, params);
                    $scope.showPageView();
                }else{
                    GillionMsg.alert("提示消息", "更新失败，请核对更新信息！");
                    return;
                }
            });
        };

        $scope.showVersions = function(row){
            GillionMsg.showUrl({
                title: '版本查看',
                url: '/html/ruleExpression/versions',
                height: 350,
                data: row,
                onClose: function(data){
                }
            });
        };

    });

    RulePackageModule.filter('statusFilter', function () {
        return function (input) {
            var valueTypeDict = ['编辑中', '已发布', '已封版'];
            return valueTypeDict[input] || '';
        };
    });

    RulePackageModule.controller('RulePackageVersionController', function($scope, Resource, GillionMsg, GillionMsgService){
        $scope.rulePackage = GillionMsgService.getInputData();
        $scope.search = {
            groupId:  $scope.rulePackage.groupId,
            artifactId: $scope.rulePackage.artifactId
        };

        $scope.publish = function() {
            var row = $scope.selectedRow;
            if (!row) {
                GillionMsg.alert('提示', '请选择版本！');
                return;
            }
            if (row.status == 1) {
                GillionMsg.alert('提示', '该版本已经是发布！');
                return;
            }
            Resource("/grule-manager/rulePackage/publish/:id", {
                id: "@id"
            }, {
                "get": {
                    "failHandler": false
                }
            }).update({
                id: row.id
            }, function (response) {
                if (response.success) {
                    GillionMsg.alert('提示消息', '切换为发布成功！', function(){
                        GillionMsgService.close();
                    });
                }
            });
        };
    });

    RulePackageModule.controller('UnitCaseController', function ($scope, GillionMsg, GillionMsgService, Arrays) {
        $scope.rulePackage = GillionMsgService.getInputData();
        $scope.search = {
            groupId:  $scope.rulePackage.groupId,
            artifactId: $scope.rulePackage.artifactId
        };

        $scope.confirm = function() {
            if ($scope.selectRows.length == 0) {
                GillionMsg.alert('提示', '请选择测试用例！');
                return;
            }
            GillionMsgService.setOutputData(Arrays.extractToArray($scope.selectRows, 'id'));
            GillionMsgService.close();
        };
    });

    return RulePackageModule;
});